package com.bytenebula.asteroid.filter;


import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.bytenebula.Consts;
import com.bytenebula.asteroid.TenantContext;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;

public class TenantFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            String tenantId = null;
            if (StpUtil.isLogin()) {
                // 先尝试从登录的Session中获取
                SaSession session = StpUtil.getTokenSession();
                Object tenantObjectId = session.get(Consts.HEADER_TENANT_ID_NAME);
                if (tenantObjectId != null) {
                    tenantId = tenantObjectId.toString();
                }
            }

            if (tenantId == null) {
                HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
                tenantId = httpRequest.getHeader(Consts.HEADER_TENANT_ID_NAME);
            }

            if (tenantId != null)
                TenantContext.setCurrentTenant(tenantId);

        } catch (RuntimeException ignored) {

        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
